package com.springcloud.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.Calendar;
import java.util.List;

/**
 *  为了更好测试自定义负载均衡
 *   根据当前系统时分的奇偶性选择负载均衡器
 */
public class TimeRule  extends AbstractLoadBalancerRule {
    /**
     *  等待
     * @param lb
     * @param key
     * @return
     */
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }
        Server server = null;
        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            // 所有有效的服务
            List<Server> upList = lb.getReachableServers();
            List<Server> allList = lb.getAllServers();
            int serverCount = allList.size();
            if (serverCount == 0) {
                return null;
            }
            // 判断是否是分是奇数还是偶数
            int currentIndex = Calendar.getInstance().get(Calendar.MINUTE);
            server = upList.get(currentIndex&1);
            System.err.println(" host port => " + server.getHostPort()  + " / key " + key);
            if (server == null) {
                Thread.yield();
                continue;
            }
            if (server.isAlive()) {
                return (server);
            }
            server = null;
            Thread.yield();
        }
        return server;
    }

    /**
     *  加载器
     * @param key
     * @return
     */
    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }

}
